package com.uhylab.uhuvinetest.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.uhylab.uhuvinetest.R;
import com.uhylab.uhuvinetest.base.UHBase;
import com.uhylab.uhuvinetest.base.UHBaseActivity;
import com.uhylab.uhuvinetest.bean.StringData;
import com.uhylab.uhuvinetest.utils.StringUtils;
import com.uhylab.uhuvinetest.utils.VolleySingleton;
import com.zhy.autolayout.AutoRelativeLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

/**
 * Created by xyb on 16/1/7 at UHylab
 *
 * @version 1.0
 */
public class UHBackPasswordActivity extends UHBaseActivity implements View.OnClickListener, Handler.Callback, CompoundButton.OnCheckedChangeListener {
    private Handler handler;
    private TextView send_sms_Button, button, title;
    private AutoRelativeLayout back_password;
    private EditText user_telphone;
    public String phString = ""; // 手机号
    String user_password_string = ""; // 密码
    // 填写从短信SDK应用后台注册得到的APPKEY
    private static String APPKEY = "dd6203e0d9e2";
    // 填写从短信SDK应用后台注册得到的APPSECRET
    private static String APPSECRET = "80bfc666a79309b55a0ef7676ec63125";
    Thread thread = null;
    private int i = 60;
    private boolean tag = true;
    private EditText user_password, user_regset, user_password_again;
    private boolean isget = false;// 是否获取验证码
    private VolleySingleton volleySingleton;
    private EventHandler eh;
    private ImageView register_back;

    @Override
    public int bindLayout() {
        return R.layout.activity_backpassword;
    }

    @Override
    public void initView(View view) {
        volleySingleton = VolleySingleton.getVolleySingleton(getApplicationContext());
        initRegisterView(view);
        initHandler();
        initIntent();
    }

    private void initIntent() {
        Intent intent = getIntent();
        if (intent != null) {
            String action = intent.getAction();
            if ("1".equals(action)) {
                title.setText("修改密码");
                button.setText("提交修改");
            }
        }
    }

    private void initRegisterView(View view) {
        send_sms_Button = (TextView) view.findViewById(R.id.send_sms_Button);
        title = (TextView) view.findViewById(R.id.title);
        button = (TextView) view.findViewById(R.id.button);
        user_telphone = (EditText) view.findViewById(R.id.user_telphone);
        back_password = (AutoRelativeLayout) view.findViewById(R.id.back_password);
        user_password = (EditText) view.findViewById(R.id.user_password);
        user_regset = (EditText) view.findViewById(R.id.user_regset);
        user_password_again = (EditText) view.findViewById(R.id.user_password_again);
        register_back = (ImageView) view.findViewById(R.id.register_back);
    }

    private void initHandler() {
        handler = new Handler(this);
    }

    private void initSDK() {
        // 初始化短信SDK
        SMSSDK.initSDK(this, APPKEY, APPSECRET, false);
        eh = new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object data) {
                Message msg = new Message();
                msg.arg1 = event;
                msg.arg2 = result;
                msg.obj = data;
                msg.what = 0;
                handler.sendMessage(msg);
            }
        };
        SMSSDK.registerEventHandler(eh);
    }

    @Override
    public void doBusiness(Context mContext) {
        send_sms_Button.setOnClickListener(this);
        back_password.setOnClickListener(this);
        register_back.setOnClickListener(this);


    }

    @Override
    public void resume() {
        initSDK();
    }

    private void isregest() {
        volleySingleton.removeRequest("isregest");
        StringRequest stringRequest = new StringRequest(Request.Method.GET, UHBase.newRegisteredUrl + "?phone=" + phString, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.e("UHBackPasswordActivity", response.toString());
                Gson gson = new Gson();
                StringData dataee = gson.fromJson(response, StringData.class);
                if (dataee.getCode().equals("0102")) {
                    Message message = new Message();
                    message.what = 1;
                    handler.sendMessage(message);
                } else {
                    Toast.makeText(UHBackPasswordActivity.this, "手机未注册", Toast.LENGTH_SHORT).show();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("UHHomeFragment", "error:" + error);
            }
        }) {
//            @Override
//            protected Map<String, String> getParams() throws AuthFailureError {
//                //在这里设置需要post的参数
//                Map<String, String> params = new HashMap<String, String>();
//                Log.e("UHRegisteredIs", phString);
//                params.put("telephone", phString);
//                return params;
//            }
        };
        volleySingleton.addQueue(stringRequest, "isregest");
    }


    private void retrievePass() {
        //在这里设置需要post的json格式的数据
        Map<String, String> params = new HashMap<String, String>();
        params.put("phone", phString);
        params.put("password", user_password_string);
        params.put("vercode", user_telphone.getText().toString());
        params.put("isthird", user_telphone.getText().toString());
        JSONObject jsonObject = new JSONObject(params);


        JsonObjectRequest retrievePass = new JsonObjectRequest(Request.Method.PUT, UHBase.newBackPassword, jsonObject, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
//                Log.e("UHHomeFragment", response);
                Gson gson = new Gson();
                try {
                    StringData dataee = gson.fromJson(response.toString(), StringData.class);
                    if (dataee.getCode().equals("0000")) {
                        Toast.makeText(UHBackPasswordActivity.this, dataee.getMsg(), Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(UHBackPasswordActivity.this, UHLogonActivity.class);
                        intent.putExtra("telephone", phString);
                        intent.putExtra("password", user_password_string);
                        startActivity(intent);
                        finish();
                    } else {
                    }
                } catch (Exception e) {

                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("UHHomeFragment", "retrievePass + error:" + error);
            }
        }) {
            //            @Override
//            protected Map<String, String> getParams() throws AuthFailureError {
//                //在这里设置需要post的参数
//                Map<String, String> params = new HashMap<String, String>();
//                params.put("telephone", phString);
//                params.put("password", user_password_string);
//                return params;
//            }
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("Accept", "application/json");
                headers.put("Content-Type", "application/json; charset=UTF-8");

                return headers;
            }

        };
        volleySingleton.addQueue(retrievePass, "Request");
    }


    @Override
    public void destroy() {
        SMSSDK.unregisterEventHandler(eh);
        volleySingleton.removeRequest("Request");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.send_sms_Button:

                phString = user_telphone.getText().toString();
                if (!TextUtils.isEmpty(phString)) {
                    if (StringUtils.isPhoneNumberValid(phString)) {
                        send_sms_Button.setText("获取中...");
                        isregest();
                    } else {
                        Toast.makeText(this, "手机号输入错误", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(this, "电话不能为空", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.back_password:
                if (isget) {
                    user_password_string = user_password.getText().toString();
                    if (!TextUtils.isEmpty(user_password_string)) {
                        if (user_password_string.length() >= 6) {

                            if (user_password_string.equals(user_password_again.getText().toString())) {
                                if (!TextUtils.isEmpty(user_regset.getText().toString())) {
                                    SMSSDK.submitVerificationCode("86", phString, user_regset.getText().toString());
                                } else {
                                    Toast.makeText(this, "验证码不能为空", Toast.LENGTH_SHORT).show();
                                }
                            } else {
                                Toast.makeText(this, "两次密码输入不一致", Toast.LENGTH_SHORT).show();
                            }


                        } else {
                            Toast.makeText(this, "请输入6位以上密码", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(this, "请获取验证码", Toast.LENGTH_SHORT).show();
                }

                break;
            case R.id.register_back:
                finish();
                break;
        }
    }

    // 获取验证码等待
    private void changeBtnGetCode() {
        thread = new Thread() {
            @Override
            public void run() {
                if (tag) {
                    while (i > 0) {
                        i--;
                        if (UHBackPasswordActivity.this == null) {
                            break;
                        }

                        UHBackPasswordActivity.this
                                .runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        send_sms_Button.setText("获取验证码("
                                                + i + ")");
                                        send_sms_Button
                                                .setClickable(false);
                                    }
                                });
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    tag = false;
                }
                i = 60;
                tag = true;
                if (UHBackPasswordActivity.this != null) {
                    UHBackPasswordActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            send_sms_Button.setText("获取验证码");
                            send_sms_Button.setClickable(true);
                        }
                    });
                }
            }
        };
        thread.start();
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case 0:
                int event = msg.arg1;
                int result = msg.arg2;
                Object data = msg.obj;
                Log.e("event", "event=" + event + "result" + result);
                if (result == SMSSDK.RESULT_COMPLETE) {
                    //短信注册成功后，返回MainActivity,然后提示新好友
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        //提交验证码成功
//                        Toast.makeText(getApplicationContext(), "提交验证码成功", Toast.LENGTH_SHORT).show();
                        volleySingleton.removeRequest("isregest");
                        retrievePass();
                    } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
//                        Toast.makeText(UHBackPasswordActivity.this, "验证码已经发送", Toast.LENGTH_SHORT).show();
                        user_regset.setText("");
                        changeBtnGetCode();
                        isget = true;
                    } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {//返回支持发送验证码的国家列表
                        Toast.makeText(UHBackPasswordActivity.this, "获取国家列表成功", Toast.LENGTH_SHORT).show();

                    }
                } else {
                    Throwable throwable = (Throwable) data;
                    throwable.printStackTrace();
                    JSONObject object;
                    try {
                        object = new JSONObject(throwable.getMessage());
                        int status = object.optInt("status");//错误代码
                        Log.e("UHRegisteredActivity", "status:" + status);
                        if (status > 0) {
                            send_sms_Button.setText("获取失败");
                            if (status == 478) {
                                Toast.makeText(this, "获取超限明日再来", Toast.LENGTH_SHORT).show();
                            } else if (status == 468) {
                                Toast.makeText(this, "验证码输入错误", Toast.LENGTH_SHORT).show();
                            } else if (status == 467) {
                                Toast.makeText(this, "校验验证码请求频繁", Toast.LENGTH_SHORT).show();
                            } else if (status == 467) {
                                Toast.makeText(this, "发送超过限额请明日再试", Toast.LENGTH_SHORT).show();
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case 1:
                SMSSDK.getVerificationCode("86", phString);
                break;
        }

        return false;


    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            user_password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            user_password.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }

    }
}
